package accs.model.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

/**
 * This class collects the HTML-input elements from a html page.
 * @author 
 */
public class HtmlFormInputCollector {
	private static final Pattern INPUT_PATTERN=Pattern.compile("<input ([^>/]*)/?>");
	private static final Pattern ATTR_PATTERN=Pattern.compile("([a-z]+)=\"([^\"]*)\"");
	
	/**
	 * Collect the key-value-pairs from the HTML-Page.
	 * @param reader Reader
	 * @param whitelist Whitelist for keys
	 * @return List of Key-Value-Pairs
	 * @throws IOException
	 */
	public static List<NameValuePair> collectInputs(Reader reader, List<String> whitelist) throws IOException {
		final List<NameValuePair> list = new ArrayList<NameValuePair>();

		BufferedReader br=new BufferedReader(reader);
		String line=null;
		
		while((line=br.readLine())!=null) {
			Matcher inputMatcher=INPUT_PATTERN.matcher(line);
			while(inputMatcher.find()) {
				String attr=inputMatcher.group(1);
				Matcher attrMatcher=ATTR_PATTERN.matcher(attr);
				
				String name="";
				String value="";
				
				while(attrMatcher.find()) {
					if(attrMatcher.group(1).equals("name")) {
						name=attrMatcher.group(2);
					} else if(attrMatcher.group(1).equals("value")) {
						value=attrMatcher.group(2).replace("&quot;","\"").replace("&#123;","{").replace("&#125;","}");
					}
				}
				
//				System.out.println("FOUND "+name);
				
				if(whitelist==null || whitelist.contains(name)) list.add(new BasicNameValuePair(name,value));
			}
		}
		
		return list;
	}
	
	public static List<NameValuePair> collectInputs(Reader r, String[] whitelist) throws IOException {
		return collectInputs(r,Arrays.asList(whitelist));
	}
	
	public static List<NameValuePair> collectInputs(Reader reader) throws IOException {
		return collectInputs(reader,(List<String>)null);
	}
}